package com.example.aslongastoday.ui.reminiscence;

import static android.content.Context.MODE_PRIVATE;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.Toast;

import com.example.aslongastoday.R;
import com.example.aslongastoday.adapter.ViewMemoryAdapter;
import com.example.aslongastoday.databinding.FragmentReminiscenceBinding;
import com.example.aslongastoday.db.dao.MemoryDao;
import com.example.aslongastoday.domain.BackLog;
import com.example.aslongastoday.domain.BackLogGroup;
import com.example.aslongastoday.domain.Memory;
import com.example.aslongastoday.ui.backlog.EditBacklogFragment;
import com.example.aslongastoday.util.TimeUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class ReminiscenceFragment extends Fragment {

    private static final String PREFS_NAME = "MyPrefsFileForMemory";
    private static final String KEY_FIRST_RUN = "firstRun";
    private FragmentReminiscenceBinding binding;
    private SearchView searchView;
    private View root;
    private RecyclerView listView;
    private List<Memory> memoryList = new ArrayList<>();
    private ViewMemoryAdapter viewMemoryAdapter;
    private MemoryDao memoryDao;
    private ItemTouchHelper itemTouchHelper;
    private ImageView addImageView;
    private ReminiscenceEditFragment reminiscenceEditFragment;
    private FragmentManager fragmentManager;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        // 初始化数据
        binding = FragmentReminiscenceBinding.inflate(inflater, container, false);
        root = binding.getRoot();
        // 初始化Dao
        memoryDao = new MemoryDao(getContext());
        // 第一次使用APP时的欢迎数据~
        onAppInit();
        // 插入测试数据
//        testDate();
        // 初始化列表的数据
        memoryList = memoryDao.getAllMemories();
        // 循环列表的初始化
        listView = root.findViewById(R.id.memory_list_rv);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        listView.setLayoutManager(layoutManager);
        viewMemoryAdapter = new ViewMemoryAdapter(memoryList,getContext(),this);
        listView.setAdapter(viewMemoryAdapter);
        // viewMemoryAdapter内部的fragment跳转和监听事件需要自己本身
        viewMemoryAdapter.setViewMemoryAdapter(this.viewMemoryAdapter);

        // 处理搜索栏的事件
        searchView = root.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                search(query);
                return true;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                // 处理搜索框文本变化事件
                return true;
            }
        });

        // 实现列表的侧滑删除当前的回忆项
         itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                Memory memory = memoryList.get(position);
                switch (direction) {
                    case ItemTouchHelper.LEFT:
                        // 侧滑删除当前的项
                        delete(memory);
                        break;
                }
            }
        });
        itemTouchHelper.attachToRecyclerView(listView);

        // 处理编辑回忆项的事件（新增）
        addImageView = root.findViewById(R.id.iv_add_memory);
        addImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reminiscenceEditFragment = new ReminiscenceEditFragment(viewMemoryAdapter,getContext());
                //数据打包
                Bundle bundle = new Bundle();
                String type = "add_memory";
                bundle.putString("type", type);
                reminiscenceEditFragment.setArguments(bundle);
                // 跳转到ReminiscenceEditFragment
                fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.add(R.id.container, reminiscenceEditFragment);
                //返回可到原处
                fragmentTransaction.setPrimaryNavigationFragment(reminiscenceEditFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });

        // 实现长按列表项可以触发编辑事项

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    /**
     *  实现在任何时刻对当前的回忆项列表的刷新
     */
    private void refreshMemoryList() {
        memoryList = memoryDao.getAllMemories();
        // 测试模糊搜索的数据库的算法是否能行  checked
//        memoryList = memoryDao.getMemoriesByName("1");
        // 要先重新设置列表然后再通知适配器刷新数据
        viewMemoryAdapter.setMemoryList(memoryList);
        viewMemoryAdapter.notifyDataSetChanged();
    }

    public void testDate(){
        // 新增数据
        for (int i = 0; i < 15; i++) {
            Date date = new Date();
            String name = "这是我的第" + (i + 1) + "" + "个回忆";
            // 可以使用R.drawable去获取图库中的资源文件的ID
            Integer iconID = new Integer(R.drawable.reminiscence_1_default_memory);
            switch (i % 5) {
                case 0:
                    iconID = new Integer(R.drawable.reminiscence_1_default_memory);
                    break;
                case 1:
                    iconID = new Integer(R.drawable.reminiscence_2_important);
                    break;
                case 2:
                    iconID = new Integer(R.drawable.reminiscence_3_anniversary);
                    break;
                case 3:
                    iconID = new Integer(R.drawable.reminiscence_4_birthdaycake1);
                    break;
                case 4:
                    iconID = new Integer(R.drawable.reminiscence_5_birthdaycake2);
                    break;
            }
            Memory memory = new Memory(date, name, iconID);
            memoryDao.addMemory(memory);
        }
    }

    /**
     * 实现对回忆项的模糊搜索
     * @param query
     */
    public void search(String query){
        // 处理搜索事件
        memoryList = "".equals(query)? memoryDao.getAllMemories():memoryDao.getMemoriesByName(query);;
        // 要先重新设置列表然后再通知适配器刷新数据
        viewMemoryAdapter.setMemoryList(memoryList);
        viewMemoryAdapter.notifyDataSetChanged();
        Toast.makeText(getActivity(), "查询成功~", Toast.LENGTH_SHORT).show();
    }

    /**
     * 实现对回忆项的删除
     * @param memory
     */
    public void delete(Memory memory){
        memoryDao.deleteMemory(memory);
        memoryList = memoryDao.getAllMemories();
        viewMemoryAdapter.setMemoryList(memoryList);
        viewMemoryAdapter.notifyDataSetChanged();
        Toast.makeText(getContext(), "删除回忆项成功!", Toast.LENGTH_SHORT).show();
    }

    public void welcomeData(){
        //获取数据
        Date date = new Date();
        String name = "这是您第一次使用回忆录!";
        // 可以使用R.drawable去获取图库中的资源文件的ID
        Integer iconID = new Integer(R.drawable.reminiscence_1_default_memory);
        Memory memory = new Memory(date, name, iconID);
        memoryDao.addMemory(memory);
    }

    public void onAppInit(){
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean firstRun = prefs.getBoolean(KEY_FIRST_RUN, true);
        if (firstRun) {
            // 在这里执行您想要在第一次安装应用程序时执行的代码块
            welcomeData();
            // 将SharedPreferences中的值设置为false，表示代码块已经执行过
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean(KEY_FIRST_RUN, false);
            editor.apply();
        }
    }

}